package lex.title.mac;

import java.awt.*;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.AbstractBorder;
import javax.swing.plaf.UIResource;

public class MacWindowBorder extends AbstractBorder implements UIResource {
	private static final MacWindowBorder instance = new MacWindowBorder();
	private boolean previousActiveState = false;
	private boolean isReallyActive = true;

	public static MacWindowBorder getInstance() {
		return instance;
	}

	public Insets getBorderInsets(Component c) {
		return new Insets(0, 1, 1, 1);
	}

	public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
		Window window = SwingUtilities.getWindowAncestor(c);
		if (window instanceof JDialog) {
			JDialog d = (JDialog) window;
			if (d.isModal()) {
				isReallyActive = true;
			} else {
				isReallyActive = isWindowRealActive(window);
			}
		} else {
			isReallyActive = isWindowRealActive(window);
		}
		int titleHeight = UIManager.getInt("InternalFrame.frameTitleHeight");
		drawLeftTop(g, isReallyActive, 4, titleHeight);
		// =========================================
		g.translate(0, titleHeight);
		drawLeft(g, isReallyActive, 4, h - titleHeight - 4);
		// =========================================
		g.translate(0, -titleHeight);
		g.translate(0, h - 4);
		drawBottom(g, isReallyActive, w, 4);
		// =========================================
		g.translate(0, -(h - 4));
		g.translate(w - 4, 0);
		drawRightTop(g, isReallyActive, 4, titleHeight);
		// =========================================
		g.translate(0, titleHeight);
		drawRight(g, isReallyActive, 4, h - titleHeight - 4);
		// =========================================
		g.translate(0, -titleHeight);
		g.translate(-(w - 4), 0);
	}

	private boolean isWindowRealActive(Window window) {
		boolean active = window.isActive();
		if (true == active) {
			previousActiveState = true;
		}
		if (false == previousActiveState && false == active) {
			active = true;
		}
		return active;
	}

	private void drawLeftTop(Graphics g, boolean isSelected, int w, int h) {
		Color c = new Color(198, 198, 198);
		g.setColor(c);
		g.fillRect(0, 0, w, h);
		return;
	}

	private void drawLeft(Graphics g, boolean isSelected, int w, int h) {
		Color c = new Color(198, 198, 198);
		g.setColor(c);
		g.fillRect(0, 0, w, h);
		return;
	}

	private void drawRightTop(Graphics g, boolean isSelected, int w, int h) {
		Color c = new Color(198, 198, 198);
		g.setColor(c);
		g.fillRect(0, 0, w, h);
		return;
	}

	private void drawRight(Graphics g, boolean isSelected, int w, int h) {
		Color c = new Color(198, 198, 198);
		g.setColor(c);
		g.fillRect(0, 0, w, h);
		return;
	}

	private void drawBottom(Graphics g, boolean isSelected, int w, int h) {
		Color c = new Color(198, 198, 198);
		g.setColor(c);
		g.fillRect(0, 0, w, h);
		return;
	}
}
